package com.lapelittle.framework.controller;

import com.lapelittle.framework.model.LoginRequest;
import com.lapelittle.framework.model.RegisterRequest;
import com.lapelittle.framework.model.LoginVO;
import com.lapelittle.framework.service.LoginService;
import com.lapelittle.framework.service.EmailService;
import com.lapelittle.framework.service.RegisterService;
import com.lapelittle.framework.common.Result;
import io.swagger.v3.oas.annotations.tags.Tag;
import io.swagger.v3.oas.annotations.Operation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Map;

@Tag(name = "认证管理")
@RestController
@RequestMapping("/auth")
public class AuthController {
    @Autowired
    private LoginService loginService;

    @Autowired
    private EmailService emailService;

    @Autowired
    private RegisterService registerService;

    @Operation(summary = "用户登录")
    @PostMapping("/login")
    public Result<LoginVO> login(@RequestBody LoginRequest request) {
        try {
            LoginVO loginVO = loginService.login(request);
            if (loginVO != null) {
                return Result.ok("登录成功", loginVO);
            }
            return Result.error("用户名或密码错误");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @Operation(summary = "用户注册")
    @PostMapping("/register")
    public Result<String> register(@RequestBody RegisterRequest request) {
        try {
            if (registerService.register(request)) {
                return Result.ok("注册成功");
            }
            return Result.error("注册失败");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @Operation(summary = "发送验证码")
    @PostMapping("/sendCode")
    public Result<String> sendCode(@RequestBody Map<String, String> params) {
        try {
            String email = params.get("email");
            emailService.sendCode(email);
            return Result.ok("验证码已发送");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }

    @Operation(summary = "退出登录")
    @PostMapping("/logout")
    public Result<String> logout() {
        try {
            return Result.ok("退出成功");
        } catch (Exception e) {
            return Result.error(e.getMessage());
        }
    }
} 